package com.soyoung.config;

/**
 * @Author : zhq
 * @since : 2018/5/2
 */
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * @ClassName: MyBatisConfig
 * @Description: Spring Boot集成Mybatis的基本入口
 * @author zhuhongqiang
 * @date 2018年5月2日14:42:48
 */
@Configuration
@MapperScan(basePackages={"com.soyoung.mapper"})
public class MyBatisConfig {

    @Autowired
    private Environment env;//直接读取本地properties文件时需要用到,读取配置中心不需要..

    @Value("${content}")
    private  String content;
    @Value("${jdbc.driver}")
    private  String driver;
    @Value("${jdbc.client_url}")
    private  String url;
    @Value("${jdbc.username}")
    private  String username;
    @Value("${jdbc.password}")
    private  String password;

    /**
     * @Title: getDataSource
     * @Description: 创建数据源
     * @param @return
     * @return DataSource
     * @throws
     */
    @Bean
    public DataSource getDataSource(){
        System.out.println(content);
        System.out.println("#########");
        System.out.println(driver);
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
        System.out.println("#########");


        Properties props = new Properties();
        props.put("driverClass", driver);
        props.put("url", url);
        props.put("username", username);
        props.put("password", password);
        DataSource dataSource = null;
        try {
            dataSource =  DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            System.out.println("getDataSource is error..");
            e.printStackTrace();
        }
        return dataSource;
    }

    /**
     * @Title: sqlSessionFactory
     * @Description:  根据数据源创建SqlSessionFactory
     * @param @param ds
     * @param @return
     * @param @throws Exception
     * @return SqlSessionFactory
     * @throws
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception{
        SqlSessionFactoryBean sfb = new SqlSessionFactoryBean();
        sfb.setDataSource(ds);
        //下边两句仅仅用于*.xml文件，如果整个持久层操作不需要使用到xml文件的话（只用注解就可以搞定），则不加
        sfb.setTypeAliasesPackage(env.getProperty("mybatis.typeAliasesPackage"));
        sfb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapperLocations")));
        return sfb.getObject();
    }
}
